// IM 能力，包括单聊、群聊、通讯录等
import NIMSDK from 'nim-web-sdk-ng/dist/NIM_UNIAPP_SDK';
import config from "@/util/config";
import ajax from "@/util/request";
import { ref, onActivated, onDeactivated, reactive } from "vue";



const setup = () => {
	
	let nim = undefined;

	const logs = reactive([]);

	const teamId = ref("");
	
	const connect = ref(false);
	
	const messages = reactive([]);

	const setConnect = async ({accid,bool = true} : {accid : string,bool: boolean}) => {
		if (bool) {
			if (!nim) {
				if (!accid) {
					console.log("accid不能为空！");
					return;
				}
				
				const res:any = await ajax({
					// 打包成app时，把下面一行注释掉
					// baseURL: "/api",
					url: "/nim/getToken",
					data: {
						t_nim_pk: accid
					},
					method: "post"
				});
				if (res.data.code < 0) {
					console.log("获取token失败");
					return;
				}
				const token = res.data.data;
				console.log("token = ",token);
				
				nim = NIMSDK.getInstance({
					appkey: config.appkey,
					account: accid,
					token,
					debugLevel: 'debug',
				});
			}
			console.log(`用户：${accid}，尝试登录。`)
			nim.connect();
			addEventListener();
		} else {
			nim.disconnect();
		}
	}

	const addEventListener = () => {
		/**
		 * 登录
		 */
		nim.on("logined", obj => {
			console.log("登录成功：", obj);
			connect.value = true;
		});
		
		/**
		 * 断开
		 */
		nim.on("disconnect", obj => {
			console.log("断开：", obj);
			connect.value = false;
		});
		
		/**
		 * 收到消息
		 */
		nim.on("msg",obj => {
			console.log("收到消息：", obj);
			messages.push(obj);
		})
	}

	/**
	 * 创建群
	 * accounts：初始成员id
	 */
	const createTeam = ({
		accounts = [],
		announcement = "测试群公告",
		inviteMode="all",
		joinMode = "noVerify",
		name = "测试群" } :
		{
			accounts ?: string[],
			announcement ?: string,
			inviteMode?: "all",
			joinMode ?: "noVerify" | "needVerify" | "rejectAll",
			name ?: string
		} = {}
	) => {
		if (!nim) {
			console.log("请先调用setConnect(true)进行初始化。");
			return;
		}

		nim.team.createTeam({
			accounts,
			announcement,
			inviteMode,
			joinMode,
			name,
			type: "advanced"
		}).then(res => {
			console.log("创建群成功：", res, ",群ID = ", res.teamId);
			logs.unshift("创建群成功,群ID = ", res.teamId);
			teamId.value = res.teamId;
		});
	}

	/**
	 * 加入群
	 * teamId：群ID
	 * ps：附言
	 */
	const applyTeam = ({
		teamId,
		ps,
	} : { teamId : string, ps ?: string }) => {
		if (!nim) {
			console.log("请先调用setConnect(true)进行初始化。");
			return;
		}
		if (!teamId) {
			console.log("teamID不能为空。");
			return;
		}
		nim.team.applyTeam({teamId,ps}).then(res => {
			console.log("加入群成功：", res, ",群ID = ", res.teamId);
			logs.unshift("加入群成功,群ID = ", res.teamId);
		},err => {
			console.log("加入群失败：", err);
			logs.unshift("加入群失败,群ID = ", teamId);
		})
	}
	
	/**
	 * 发送消息
	 * body: 消息内容
	 * to：消息发送目标（用户ID或teamID）
	 * scene: 消息类型（群聊、p2p）
	 */
	const sendMessage = (
	{body,
	to,
	scene = "team",
	}: {body: string,to: string,scene:"p2p" | "team" | "superTeam"}) => {
		if (!nim) {
			console.log("请先调用setConnect(true)进行初始化。");
			return;
		}
		if (!body || !to) {
			console.log("发送内容或发送目标为空");
			return;
		}
		
		nim.msg.sendTextMsg({
			body,
			to,
			scene,
		});
		console.log("消息发送完毕");
	}

	return {
		setConnect, createTeam, teamId,applyTeam,connect,sendMessage,messages
	}

}

export default setup;